package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"wechat/models/mysql"

	"wechat/userrpc/internal/svc"
	"wechat/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserUpdateLogic {
	return &UserUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserUpdateLogic) UserUpdate(in *userrpc.UserUpdateRequest) (*userrpc.UserUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	mysql.DB.Where("id = ?", in.UserId).Find(&user)

	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在")
	}

	var findUser mysql.User
	mysql.DB.Debug().Where("id != ?", in.UserId).Where("wechat_name = ?", in.WechatName).Find(&findUser)

	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前微信号已被人使用 ,请重新输入")
	}

	m := mysql.User{
		Model:      gorm.Model{ID: user.ID},
		HeadImage:  in.HeadImage,
		Name:       in.Name,
		Address:    in.Address,
		WechatName: in.WechatName,
	}

	mysql.DB.Debug().Updates(&m)

	return &userrpc.UserUpdateResponse{Id: int64(user.ID)}, nil
}
